package cn.xfdzx.android.apps.shop.fragment;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.activity.login.OneLoginMainActivity;
import cn.xfdzx.android.apps.shop.adapter.ShopInGoodListAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpFragment;
import cn.xfdzx.android.apps.shop.bean.GoodsLiblaryListBean;
import cn.xfdzx.android.apps.shop.bean.GoodsUpStateBeen;
import cn.xfdzx.android.apps.shop.bean.OneCategoryBeen;
import cn.xfdzx.android.apps.shop.bean.ShopAddGoodTypeBeen;
import cn.xfdzx.android.apps.shop.bean.ShopInGoodListBeen;
import cn.xfdzx.android.apps.shop.bean.UpdateNumPriceBeen;
import cn.xfdzx.android.apps.shop.contract.ItemClickListener;
import cn.xfdzx.android.apps.shop.contract.ShopInGoodListContract;
import cn.xfdzx.android.apps.shop.evenbus.SearchGoodsContentMessage;
import cn.xfdzx.android.apps.shop.evenbus.UpdateMessage;
import cn.xfdzx.android.apps.shop.presenter.ShopInGoodListPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.KeybordUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.UtilsData;

import static cn.xfdzx.android.apps.shop.apps.Constants.APP_TOKEN;


/**
 * @author gzk
 * @date 2020/3/26 0026
 * description：商家入驻 商品管理
 */
public class ShopInGoodFragment extends BaseMvpFragment<ShopInGoodListPresenter> implements ShopInGoodListContract.View, ItemClickListener {

    RecyclerView rvAllOrder;
    SmartRefreshLayout mRefreshLayout;

    TextView tvHint;
    LinearLayout llHint;
    private ShopInGoodListAdapter orderListAdapter;
    private int page = 1;
    private int limit = Constants.LIMIT;
    private String orderType, styleType;
    private List<ShopInGoodListBeen.DataBean> mList = new ArrayList();
    private Dialog dialog;
    private int now_position;
    private EditText ettGoodPrice, ettGoodYouhuiPrice, ettKucun;
    private TextView tvDialogQueren;
    private int isSearch;
    private String searchMessage;
    @Override
    protected void initView(View view) {
        rvAllOrder = view.findViewById(R.id.rv_all_order);
        mRefreshLayout = view.findViewById(R.id.refreshLayout);
        tvHint = view.findViewById(R.id.tv_hint);
        llHint = view.findViewById(R.id.ll_hint);
        EventBus.getDefault().register(this);
        tvHint.setText("没有发现商品哦");
        orderType = getArguments().getString("orderType");
        styleType = getArguments().getString("styleType");
        mPresenter = new ShopInGoodListPresenter();
        mPresenter.attachView(this);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvAllOrder.setLayoutManager(linearLayoutManager);
        rvAllOrder.setItemAnimator(new DefaultItemAnimator());
        orderListAdapter = new ShopInGoodListAdapter(getActivity(), mList, mPresenter, styleType);
        orderListAdapter.setItemClickListener(this::onItemClick);
        rvAllOrder.setAdapter(orderListAdapter);


        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                page = 1;
                Map<String,Object> map = new HashMap<>();
                map.put("page",page + "");
                map.put("limit",limit + "");
                map.put("type",orderType);
                if (EmptyUtil.isNotEmpty(searchMessage)){
                    map.put("keyword",searchMessage);
                }
                mPresenter.initData(true, false, map);
            }
        });
        dialog = new Dialog(getActivity(), R.style.ExitDialog);
        View layout = View.inflate(getActivity(), R.layout.dialog_good_bianji, null);
        dialog.setContentView(layout);
        dialog.setCanceledOnTouchOutside(true);
        layout.findViewById(R.id.tvw_dialog_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        ettGoodPrice = layout.findViewById(R.id.ett_good_price);
        ettGoodYouhuiPrice = layout.findViewById(R.id.ett_good_youhui_price);
        ettKucun = layout.findViewById(R.id.ett_kucun);
        tvDialogQueren = layout.findViewById(R.id.tv_dialog_queren);
        if (styleType.equals("0")) {
            tvDialogQueren.setTextColor(getResources().getColor(R.color.color_FB9129));
        } else {
            tvDialogQueren.setTextColor(getResources().getColor(R.color.color_02C557));
        }
        tvDialogQueren.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mPresenter.updateNumPrice(mList.get(now_position).getId() + "", ettGoodPrice.getText().toString().trim(), ettKucun.getText().toString().trim(), ettGoodYouhuiPrice.getText().toString().trim());
            }
        });

    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_all_order;
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(getActivity());
        }
    }


    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();


    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void onGoodListSuccess(ShopInGoodListBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (page == 1) {
                mList.clear();
                mRefreshLayout.setNoMoreData(false);
                mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                        Map<String,Object> map = new HashMap<>();
                        map.put("page",page + "");
                        map.put("limit",limit + "");
                        map.put("type",orderType);
                        if (isSearch==1){//搜索商品
                            map.put("keyword",searchMessage);
                        }
                        mPresenter.initData(false, false, map);
                    }
                });
            }
            if (bean.getData().size() == 0) {
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                page++;
            }
            mList.addAll(bean.getData());
            orderListAdapter.notifyDataSetChanged();
            if (mList.size()==0){
                llHint.setVisibility(View.VISIBLE);
            }else {
                llHint.setVisibility(View.GONE);
            }
        } else {
            if (bean.getStatus() == Constants.LOGIN_CODE) {
                UtilsData.getPreference(getActivity(), "login").remove("head_url");
                UtilsData.getPreference(getActivity(), "login").remove("nickname");
                UtilsData.getPreference(getActivity(), "login").remove("is_store");
                UtilsData.getPreference(getActivity(), "login").remove("token");
                APP_TOKEN = "";
                Intent intent = new Intent(getActivity(), OneLoginMainActivity.class);
                startActivity(intent);
                return;
            }
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void finishRefresh() {
        mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    public void onGoodsUpStateSuccess(GoodsUpStateBeen bean, int position) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            if (mList.get(position).getState() == 0) {
                mList.get(position).setState(1);
            } else {
                mList.get(position).setState(0);
            }
            orderListAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void onUpdateNumPriceSuccess(UpdateNumPriceBeen bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {
            mList.get(now_position).setMarketprice(ettGoodPrice.getText().toString().trim());
            mList.get(now_position).setDiscountprice(ettGoodYouhuiPrice.getText().toString().trim());
            mList.get(now_position).setStock(Integer.parseInt(ettKucun.getText().toString().trim()));
            orderListAdapter.notifyDataSetChanged();
        } else {
            Toast.makeText(getActivity(), bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getLibraryListSuccess(GoodsLiblaryListBean bean) {

    }

    @Override
    public void getOneCategorySuccess(OneCategoryBeen bean) {

    }

    @Override
    public void addGoodsSuccess(OneCategoryBeen bean,String catoryId) {

    }

    @Override
    public void getCategoryListSuccess(ShopAddGoodTypeBeen bean) {

    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void XXX(UpdateMessage messageEvent) {
        if (messageEvent.getMessage().equals(orderType)) {
            page = 1;
            Map<String,Object> map = new HashMap<>();
            map.put("page",page + "");
            map.put("limit",limit + "");
            map.put("type",orderType);
            if (EmptyUtil.isNotEmpty(searchMessage)){
                map.put("keyword",searchMessage);
            }
            mPresenter.initData(true, true, map);
        }
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onSearchEvent(SearchGoodsContentMessage messageEvent) {
        if (String.valueOf(messageEvent.getPage()).equals(orderType)){
            isSearch = messageEvent.getIsSearch();
            if (messageEvent.getIsSearch()==0){//删除了搜索内容
                page = 1;
                searchMessage = "";
                Map<String,Object> map = new HashMap<>();
                map.put("page",page + "");
                map.put("limit",limit + "");
                map.put("type",orderType);
                mPresenter.initData(true, false, map);
                llHint.setVisibility(View.GONE);
            }else {//点击了搜索
                KeybordUtil.closeKeybord(getActivity());
                searchMessage = messageEvent.getSearchMessage();
                page = 1;
                Map<String,Object> map = new HashMap<>();
                map.put("page",page + "");
                map.put("limit",limit + "");
                map.put("type",orderType);
                map.put("keyword",messageEvent.getSearchMessage());
                mPresenter.initData(true, false, map);

            }
        }else {
            if (messageEvent.getIsSearch()==0){
                searchMessage = "";
            }else {
                searchMessage = messageEvent.getSearchMessage();
            }

        }

    }

    public static ShopInGoodFragment newInstance(String orderType, String styleType) {
        Bundle bundle = new Bundle();
        bundle.putString("orderType", orderType + "");
        bundle.putString("styleType", styleType + "");
        ShopInGoodFragment fragment = new ShopInGoodFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        mList.clear();
        mList = null;
        super.onDestroy();
    }

    @Override
    public void onItemClick(int position) {
        dialog.show();
        ettGoodPrice.setText(mList.get(position).getMarketprice());
        ettGoodYouhuiPrice.setText(mList.get(position).getDiscountprice());
        ettKucun.setText(mList.get(position).getStock() + "");
        now_position = position;
    }


}
